package cn.yitun.chat.yitunchatbasesdk.server.im.dispatcher.impl;

import cn.yitun.chat.yitunactiondispatch.common.ApplyInfo;
import cn.yitun.chat.yitunactiondispatch.extend.ActionInterceptor;
import cn.yitun.chat.yitunactiondispatch.extend.ActionRequest;
import cn.yitun.chat.yitunactiondispatch.extend.ActionResponse;
import cn.yitun.chat.yitunactiondispatch.extend.ArgumentBox;
import cn.yitun.chat.yituncommonmessage.impl.HeadImpl;
import cn.yitun.chat.yituncommonmessage.result.ResultMessage;
import cn.yitun.chat.yituncommonmessage.server.Result;
import cn.yitun.chat.yituncommonmessage.server.ServerHead;
import cn.yitun.chat.yitungeneral.annotation.action.MethodMapping;
import cn.yitun.chat.yitunnetsession.session.SocketSession;

import java.lang.reflect.Method;

/**
 * Date 2019-01-12 12:34:09<br>
 * Description
 * @author yitun
 * @since 1.1
 */

public class HandlerAuthInterceptor implements ActionInterceptor {

	@Override
	public ApplyInfo previous(ActionRequest request, ActionResponse response, ArgumentBox argumentBox) {
		Object value = null;
		SocketSession socketSession = argumentBox.get(SocketSession.class);
		ServerHead resultHead = argumentBox.get(ServerHead.class);

		Method method = request.getActionMethod().getMethod();
		boolean isAuth = interceptor(method, socketSession);
		if (!isAuth) {
			Result r = new Result();
			r.setCode(HeadImpl.code_fail);
			r.setMessage("您没有权限访问！");
			
			resultHead.setResult(r);
			resultHead.setTimestamp(System.currentTimeMillis());

			ResultMessage m = new ResultMessage();
			m.setHead(resultHead);
			value = (m);
		}
		ApplyInfo applyInfo = new ApplyInfo();
		applyInfo.setApprove(isAuth);
		applyInfo.setValue(value);
		return applyInfo;
	}

	private boolean interceptor(Method method, SocketSession socketSession) {
		boolean isAuth = false;
		if (!isIntercept(method)) {
			isAuth = true;
		} else {
			isAuth = socketSession.isAuth();
		}
		return isAuth;
	}

	private boolean isIntercept(Method method) {
		boolean isIntercept = true;
		MethodMapping mm = method.getAnnotation(MethodMapping.class);
		if (null != mm) {
			isIntercept = mm.isIntercept();
		}
		return isIntercept;
	}
}
